package com.ruoyi.web.controller.common;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lly835.bestpay.config.WxPayConfig;
import com.lly835.bestpay.enums.BestPayPlatformEnum;
import com.lly835.bestpay.enums.BestPayTypeEnum;
import com.lly835.bestpay.model.PayRequest;
import com.lly835.bestpay.model.PayResponse;
import com.lly835.bestpay.model.RefundRequest;
import com.lly835.bestpay.model.RefundResponse;
import com.lly835.bestpay.service.impl.BestPayServiceImpl;
import com.lly835.bestpay.utils.JsonUtil;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.HttpOutSideUtil;
import com.ruoyi.common.utils.IdWorker;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.base64.BASE64DecodedMultipartFile;
import com.ruoyi.common.utils.base64.Base64StrToImage;
import com.ruoyi.common.utils.bean.FootBean;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.html.HTMLToPDFUtils;
import com.ruoyi.common.utils.sms.SmsUtils;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.system.domain.Spread;
import com.ruoyi.system.domain.SysDevice;
import com.ruoyi.system.domain.SysDeviceData;
import com.ruoyi.system.domain.SysDeviceOmen;
import com.ruoyi.system.domain.SysOrder;
import com.ruoyi.system.domain.SurverAnswer;
import com.ruoyi.system.service.ICommonService;
import com.ruoyi.system.service.ISysDeviceDataService;
import com.ruoyi.system.service.ISysDeviceService;
import com.ruoyi.system.service.ISysOrderService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.SpreadService;
import com.ruoyi.web.core.config.mqtt.MqttUtil;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import com.ruoyi.web.core.config.mqtt.MessageListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ruoyi.common.utils.ShiroUtils.getSysUser;

/**
 * 通用请求处理
 *
 * @author ruoyi
 */
@Controller
@RequestMapping("/common")
public class CommonController
{
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDeviceService deviceService;

    @Autowired
    private ISysDeviceDataService deviceDataService;

    @Autowired
    private ISysOrderService orderService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private BestPayServiceImpl bestPayService;

    @Autowired
    private SpreadService spreadService;

    @Autowired
    private ICommonService commonService;

    @Autowired
    private JavaMailSender javaMailSender;

    private static final String FILE_DELIMETER = ",";

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @GetMapping("/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.checkAllowDownload(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = RuoYiConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用上传请求（多个）
     */
    @PostMapping("/uploads")
    @ResponseBody
    public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile file : files)
            {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 本地资源通用下载
     */
    @GetMapping("/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        try
        {
            if (!FileUtils.checkAllowDownload(resource))
            {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = RuoYiConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用请求设备（多个）
     */
    @PostMapping("/queryDevice")
    @ResponseBody
    public AjaxResult queryDevice() throws Exception {
        List<SysDevice> deviceList = deviceService.selectDeviceList(new SysDevice());
        return AjaxResult.success(deviceList);

    }

    /**
     * 设备商城
     */
    @GetMapping("/shop")
    public ModelAndView shop()
    {
        ModelAndView model = new ModelAndView("common/shop");
//        SysDevice sysDevice = new SysDevice();
//        sysDevice.setStatus("1");
//        model.addObject("deviceList",deviceService.selectDeviceList(sysDevice));
        return model;
    }

    /**
     * 订单
     */
    @GetMapping("/order")
    public ModelAndView order()
    {
        ModelAndView model = new ModelAndView("common/order");
//        SysDevice sysDevice = new SysDevice();
//        sysDevice.setStatus("1");
//        model.addObject("deviceList",deviceService.selectDeviceList(sysDevice));
        return model;
    }

    /**
     * 微信登录
     */
    @ApiOperation("微信登录")
    @PostMapping("/sunWxLogin")
    @ResponseBody
    public AjaxResult sunWxLogin(@RequestParam("code") String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", "wxa1984bf31494d947");
        paramMap.put("secret", "825354d156168501781aef7c7f3cbd8b");
        paramMap.put("js_code", code);
        paramMap.put("grant_type", "authorization_code");
        String result = HttpOutSideUtil.getByHttp(url,paramMap);
        if(StringUtils.isNull(result)){
            paramMap.put("appid", "wxadedb1c9473daae2");
            paramMap.put("secret", "8832daaf6edb3f4075917445671a9de3");
            paramMap.put("js_code", code);
            paramMap.put("grant_type", "authorization_code");
            result = HttpOutSideUtil.getByHttp(url,paramMap);
        }
        return AjaxResult.success(result);
    }

    /**
     * 微信登录
     */
    @ApiOperation("微信登录")
    @PostMapping("/wxLogin")
    @ResponseBody
    public AjaxResult wxLogin(@RequestParam("code") String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", "wxadedb1c9473daae2");
        paramMap.put("secret", "8832daaf6edb3f4075917445671a9de3");
        paramMap.put("js_code", code);
        paramMap.put("grant_type", "authorization_code");
        String result = HttpOutSideUtil.getByHttp(url,paramMap);
        return AjaxResult.success(result);
    }

    /**
     * 微信登录
     */
    @ApiOperation("微信登录")
    @PostMapping("/biologyWxLogin")
    @ResponseBody
    public AjaxResult biologyWxLogin(@RequestParam("code") String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> paramMap = new HashMap<>();
//        paramMap.put("appid", "wx9144a8d802d22aaa");
//        paramMap.put("secret", "755af0ee1229fe9a6d346f50b44141e0");
        paramMap.put("appid", "wxa1984bf31494d947");
        paramMap.put("secret", "825354d156168501781aef7c7f3cbd8b");
        paramMap.put("js_code", code);
        paramMap.put("grant_type", "authorization_code");
        String result = HttpOutSideUtil.getByHttp(url,paramMap);
        return AjaxResult.success(result);
    }

    /**
     * 微信登录
     */
    @ApiOperation("微信登录")
    @PostMapping("/songWxLogin")
    @ResponseBody
    public AjaxResult songWxLogin(@RequestParam("code") String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> paramMap = new HashMap<>();
//        paramMap.put("appid", "wx9144a8d802d22aaa");
//        paramMap.put("secret", "755af0ee1229fe9a6d346f50b44141e0");
        paramMap.put("appid", "wx370febb4ce6c9f38");
        paramMap.put("secret", "4b58c0fe793536b1d9883d036c81922b");
        paramMap.put("js_code", code);
        paramMap.put("grant_type", "authorization_code");
        String result = HttpOutSideUtil.getByHttp(url,paramMap);
        return AjaxResult.success(result);
    }

    /**l
     * 新增用户信息
     */
    @ApiOperation("查询用户信息")
    @PostMapping("/queryUserByOpenid")
    @ResponseBody
    public AjaxResult queryUserByOpenid(@RequestParam("openid") String openid) throws Exception {
        return AjaxResult.success(userService.queryUserByOpenid(openid));
    }

    /**l
     * 新增用户信息
     */
    @ApiOperation("新增用户信息")
    @PostMapping("/addUser")
    @ResponseBody
    public AjaxResult addUser(@RequestParam("openid") String openid, @RequestParam("phone") String phone, @RequestParam("name") String name, @RequestParam("sex") String sex, @RequestParam("age") String age, @RequestParam("height") String height, @RequestParam("weight") String weight, @RequestParam("roleId") int roleId, @RequestParam("userId") Long userId, @RequestParam("shoe") String shoe, @RequestParam("foot") String foot, @RequestParam("medical") String medical) throws Exception {
        return AjaxResult.success(userService.addUser(openid,phone,name,sex,age,height,weight,roleId,userId,shoe,foot,medical));
    }

    /**+-
     * 新增足底数据
     */
    @ApiOperation("新增足底数据")
    @PostMapping("/addPlantarData")
    @ResponseBody
    public AjaxResult addPlantarData(@RequestBody(required=false) Map<String,Object> plantar) {
        return AjaxResult.success(deviceDataService.addPlantarData(plantar));
    }

    /**
     * 获取足底数据
     */
    @ApiOperation("获取足底数据")
    @GetMapping("/queryPlantarData")
    @ResponseBody
    public AjaxResult queryPlantarData(@RequestParam(value = "userId", required = false) Long userId, @RequestParam(value = "roleId", required = false) String roleId) {
        return AjaxResult.success(deviceDataService.queryPlantarData(userId,roleId));
    }

    /**
     * 获取医生信息
     */
    @ApiOperation("获取医生信息")
    @PostMapping("/queryUserList")
    @ResponseBody
    public AjaxResult queryUserList() {
        return AjaxResult.success(userService.queryUserList());
    }

    /**
     * 发起支付
     */
    @GetMapping(value = "/pay")
    @ResponseBody
    public PayResponse pay(@RequestParam String orderId) throws UnsupportedEncodingException {
        //支付请求参数
        PayRequest request = new PayRequest();
        request.setPayTypeEnum(BestPayTypeEnum.ALIPAY_PC);
        request.setOrderId(orderId);
        request.setOrderAmount(0.01);
        request.setOrderName("最好的支付sdk");
        request.setAttach("这里是附加的信息");
        log.info("【发起支付】request={}", JsonUtil.toJson(request));

        PayResponse payResponse = bestPayService.pay(request);
        String result = URLDecoder.decode(payResponse.getBody(),"UTF-8");
        log.info("【发起支付】response={}", result);
        return payResponse;
    }

    /**
     * 异步回调
     * @return
     */
    @PostMapping(value = "/notify")
    @ResponseBody
    public Object notify(@RequestBody String notifyData) {
        log.info("【异步通知】支付平台的数据request={}", notifyData);
        PayResponse response = bestPayService.asyncNotify(notifyData);
        log.info("【异步通知】处理后的数据data={}", JsonUtil.toJson(response));

        SysOrder order = orderService.selectOrderByOrderCode(response.getOrderId());
        //返回成功信息给支付平台，否则会不停的异步通知
        if (response.getPayPlatformEnum() == BestPayPlatformEnum.WX) {
//            return new ModelAndView("common/successForWx");
            order.setTradeNo(response.getOutTradeNo());
            order.setPlatform(response.getPayPlatformEnum().getCode());
            order.setPayStatus("TRADE_SUCCESS");
            order.setUpdateBy("admin");
            order.setUpdateTime(new Date());
            orderService.update(order);
            return AjaxResult.success();
        }else if (response.getPayPlatformEnum() == BestPayPlatformEnum.ALIPAY) {
//            return new ModelAndView("common/successForAlipay");
            order.setTradeNo(response.getOutTradeNo());
            order.setPlatform(response.getPayPlatformEnum().getCode());
            order.setPayStatus("TRADE_SUCCESS");
            order.setUpdateBy("admin");
            order.setUpdateTime(new Date());
            orderService.update(order);
            return "success";
        }
        throw new RuntimeException("错误的支付平台");
    }

    @GetMapping("/refund")
    @ResponseBody
    public RefundResponse refund(@RequestParam String orderId) {
        SysOrder order = orderService.selectOrderByOrderCode(orderId);
        RefundRequest request = new RefundRequest();
        request.setOrderId(orderId);
        if("wx".equals(order.getPlatform())) {
            request.setPayTypeEnum(BestPayTypeEnum.WXPAY_NATIVE);
        }else if("alipay".equals(order.getPlatform())){
            request.setPayTypeEnum(BestPayTypeEnum.ALIPAY_PC);
        }
        request.setOrderAmount(order.getAmount());
        RefundResponse response = bestPayService.refund(request);
        return response;
    }

    /**
     * 同步回调
     * @return
     */
    @GetMapping(value = "/return")
    public ModelAndView payReturn() {
        return new ModelAndView("common/toPay");
    }

    /**
     * 资讯医生列表
     */
    @ApiOperation("资讯医生列表")
    @PostMapping("/doctorList")
    @ResponseBody
    public AjaxResult doctorList() {
        return AjaxResult.success(userService.selectDoctorList());
    }

    /**
     * 科普资讯列表
     */
    @ApiOperation("科普资讯列表")
    @PostMapping("/spreadList")
    @ResponseBody
    public AjaxResult spreadList() {
        return AjaxResult.success(spreadService.queryAll(new Spread()));
    }

    /**
     * 商城列表
     */
    @ApiOperation("商城列表")
    @PostMapping("/shopList")
    @ResponseBody
    public AjaxResult shopList() {
        SysDevice device = new SysDevice();
        device.setStatus("1");
        return AjaxResult.success(deviceService.selectDeviceList(device));
    }

    /**
     * 商城列表
     */
    @ApiOperation("订单列表")
    @PostMapping("/orderList")
    @ResponseBody
    public AjaxResult orderList(@RequestParam Long userId) {
        SysOrder order = new SysOrder();
        order.setUserId(userId);
        return AjaxResult.success(orderService.selectDeviceList(order));
    }

    /**
     * 微信小程序支付
     */
    @SneakyThrows
    @ApiOperation("微信小程序支付")
    @PostMapping("/appletPay")
    @ResponseBody
    public AjaxResult appletPay(@RequestParam Long userId, @RequestParam Long deviceId, @RequestParam String phone, @RequestParam String address, @RequestParam String remark) {
        String orderId = String.valueOf(new IdWorker().nextId());
        SysDevice device = deviceService.selectDeviceById(deviceId);
        SysUser user = userService.selectUserById(userId);
        PayRequest request = new PayRequest();
        request.setPayTypeEnum(BestPayTypeEnum.WXPAY_MINI);
        request.setOrderId(orderId);
        Double amount = device.getPrice();
        request.setOrderAmount(amount);
        request.setOrderName(device.getDeviceName());
        request.setAttach(device.getDeviceName());
        request.setOpenid(user.getOpenid());
        log.info("【发起支付】request={}", JsonUtil.toJson(request));
        WxPayConfig wxPayConfig = new WxPayConfig();
        wxPayConfig.setAppId("wxa1984bf31494d947");
        wxPayConfig.setMiniAppId("wxadedb1c9473daae2");
        wxPayConfig.setMchId("1623831810");
        wxPayConfig.setMchKey("825354d156168501781aef7c7f3cbd8b");
        wxPayConfig.setKeyPath("/home/sunfu_back/apiclient_cert.p12");
//        wxPayConfig.setKeyPath("C:/msznyl/apiclient_cert.p12");
        wxPayConfig.setNotifyUrl("https://sunfu.xdkdate.com/common/notify");
//        wxPayConfig.setNotifyUrl("https://www.bythealthy.com/sunfu/common/notify");
        wxPayConfig.setAppAppId("wxadedb1c9473daae2");
        bestPayService.setWxPayConfig(wxPayConfig);
        PayResponse payResponse = bestPayService.pay(request);
        deviceService.pay(device,user,orderId,phone,address,amount,remark);
        return AjaxResult.success(payResponse);
    }

    /**
     * 微信小程序支付
     */
    @SneakyThrows
    @ApiOperation("微信小程序支付")
    @PostMapping("/sunAppletPay")
    @ResponseBody
    public AjaxResult sunAppletPay(@RequestParam Long userId, @RequestParam Long deviceId, @RequestParam String phone, @RequestParam String address, @RequestParam String remark) {
        String orderId = String.valueOf(new IdWorker().nextId());
        SysDevice device = deviceService.selectDeviceById(deviceId);
        SysUser user = userService.selectUserById(userId);
        PayRequest request = new PayRequest();
        request.setPayTypeEnum(BestPayTypeEnum.WXPAY_MINI);
        request.setOrderId(orderId);
        Double amount = device.getPrice();
        request.setOrderAmount(amount);
        request.setOrderName(device.getDeviceName());
        request.setAttach(device.getDeviceName());
        request.setOpenid(user.getOpenid());
        log.info("【发起支付】request={}", JsonUtil.toJson(request));
        WxPayConfig wxPayConfig = new WxPayConfig();
        wxPayConfig.setAppId("wxa1984bf31494d947");
        wxPayConfig.setMiniAppId("wxa1984bf31494d947");
        wxPayConfig.setMchId("1623831810");
        wxPayConfig.setMchKey("825354d156168501781aef7c7f3cbd8b");
        wxPayConfig.setKeyPath("/home/sunfu_back/apiclient_cert.p12");
//        wxPayConfig.setKeyPath("C:/msznyl/apiclient_cert.p12");
        wxPayConfig.setNotifyUrl("https://sunfu.xdkdate.com/common/notify");
//        wxPayConfig.setNotifyUrl("https://www.bythealthy.com/sunfu/common/notify");
        wxPayConfig.setAppAppId("wxa1984bf31494d947");
        bestPayService.setWxPayConfig(wxPayConfig);
        PayResponse payResponse = bestPayService.pay(request);
        deviceService.pay(device,user,orderId,phone,address,amount,remark);
        return AjaxResult.success(payResponse);
    }

    /**
     * 微信小程序支付
     */
    @SneakyThrows
    @ApiOperation("微信小程序支付")
    @PostMapping("/biologyAppletPay")
    @ResponseBody
    public AjaxResult biologyAppletPay(@RequestParam Long userId, @RequestParam Long deviceId, @RequestParam String phone, @RequestParam String address, @RequestParam String remark) {
        String orderId = String.valueOf(new IdWorker().nextId());
        SysDevice device = deviceService.selectDeviceById(deviceId);
        SysUser user = userService.selectUserById(userId);
        PayRequest request = new PayRequest();
        request.setPayTypeEnum(BestPayTypeEnum.WXPAY_MINI);
        request.setOrderId(orderId);
        Double amount = device.getPrice();
        request.setOrderAmount(amount);
        request.setOrderName(device.getDeviceName());
        request.setAttach(device.getDeviceName());
        request.setOpenid(user.getOpenid());
        log.info("【发起支付】request={}", JsonUtil.toJson(request));
        WxPayConfig wxPayConfig = new WxPayConfig();
        wxPayConfig.setAppId("wxa1984bf31494d947");
        wxPayConfig.setMiniAppId("wxa1984bf31494d947");
        wxPayConfig.setMchId("1623831810");
        wxPayConfig.setMchKey("825354d156168501781aef7c7f3cbd8b");
        wxPayConfig.setKeyPath("/home/sunfu_back/apiclient_cert.p12");
//        wxPayConfig.setKeyPath("C:/msznyl/apiclient_cert.p12");
        wxPayConfig.setNotifyUrl("https://sunfu.xdkdate.com/common/notify");
//        wxPayConfig.setNotifyUrl("https://www.bythealthy.com/sunfu/common/notify");
        wxPayConfig.setAppAppId("wxa1984bf31494d947");
        bestPayService.setWxPayConfig(wxPayConfig);
        PayResponse payResponse = bestPayService.pay(request);
        deviceService.pay(device,user,orderId,phone,address,amount,remark);
        return AjaxResult.success(payResponse);
    }

    @PostMapping("/login")
    @ResponseBody
    public AjaxResult ajaxLogin(String username, String password)
    {
        SysUser user = userService.selectUserByLoginName(username);
        String pass = passwordService.encryptPassword(username,password,user.getSalt());
        if(pass.equals(user.getPassword())){
            return AjaxResult.success();
        }else{
            return AjaxResult.error("密码错误");
        }
    }

    @ApiOperation("获取足底数据")
    @GetMapping("/queryPlantarDataByUser")
    @ResponseBody
    public AjaxResult queryPlantarDataByUser(@RequestParam Long userId)
    {
        return AjaxResult.success(deviceDataService.queryPlantarDataByUser(userId));
    }

    @RequestMapping("/testImg")
    @ResponseBody
    public AjaxResult testImg() throws InterruptedException {
        HTMLToPDFUtils.htmlToImg("https://sunfu.xdkdate.com/common/pdfimg?deviceDataId=6351","/home/sunfu_back/uploadPath/testImg.jpg", "--width 348 --height 355");
//        HTMLToPDFUtils.htmlToImg("https://www.bythealthy.com/sunfu/common/pdfimg?deviceDataId=6351","C:/msznyl/uploadPath/testImg.jpg", "--width 348 --height 355");
        return AjaxResult.success();
    }

    @RequestMapping("report")
    @ResponseBody
    public AjaxResult report(@RequestParam Long deviceDataId){
        HTMLToPDFUtils.htmlToImg("https://sunfu.xdkdate.com/common/toReport?deviceDataId=" + deviceDataId,"/home/sunfu_back/uploadPath/" + deviceDataId + "-report.jpg","--width 720 --height 950");
//        HTMLToPDFUtils.htmlToImg("https://www.bythealthy.com/sunfu/common/toReport?deviceDataId=" + deviceDataId,"C:/msznyl/uploadPath/" + deviceDataId + "-report.jpg","--width 720 --height 950");
        return AjaxResult.success("https://sunfu.xdkdate.com/profile/" + deviceDataId + "-report.jpg");
//        return AjaxResult.success("https://www.bythealthy.com/sunfu/profile/" + deviceDataId + "-report.jpg");
    }

    @RequestMapping("toReport")
    public ModelAndView toReport(@RequestParam Long deviceDataId){
        ModelAndView mav = new ModelAndView();
        SysDeviceData sysDeviceData = deviceDataService.queryById(deviceDataId);
        mav.setViewName("report");
        mav.addObject("deviceDataId",deviceDataId);
        SysUser user = userService.selectUserById(sysDeviceData.getUserId());
        mav.addObject("user",user);
        if("0".equals(user.getSex())){
            mav.addObject("sex","男");
        }else if("1".equals(user.getSex())){
            mav.addObject("sex","女");
        }else{
            mav.addObject("sex","未知");
        }
        return mav;
    }

    @RequestMapping("pdfimg")
    public ModelAndView pdfimg(@RequestParam Long deviceDataId){
        ModelAndView mav = new ModelAndView();
        mav.setViewName("pdfimg");
        mav.addObject("deviceDataId",deviceDataId);
        return mav;
    }

    @RequestMapping("pdfimgData")
    @ResponseBody
    public AjaxResult pdfimgData(@RequestParam Long deviceDataId){
        Map<String,Object> mav = new HashMap<>();
        SysDeviceData sysDeviceData = deviceDataService.queryById(deviceDataId);
        String value = sysDeviceData.getDeviceDataValue();
        String[] data = value.split(",");
        if(data.length == 8){
            mav.put("pointNum",4);

            for (int i = 1; i <= 4; i++) {
                mav.put("data" + i + "left",data[i-1]);
                mav.put("data" + i + "right",data[i+3]);
            }
            for (int i = 5; i <= 8; i++) {
                mav.put("data" + i + "left",0);
                mav.put("data" + i + "right",0);
            }
        }else{
            mav.put("pointNum",8);
            String dataStr = "";
            for (String a:data) {
                if(StringUtils.isInteger(a)) {
                    if (Integer.parseInt(a) < 50) {
                        dataStr += 0;
                    } else {
                        dataStr += 1;
                    }
                }
            }
            String[] str = new String[16];
            for (int i = 0; i < 16; i++) {
                str[i] = dataStr.substring(i*2,i*2+2);
            }
            for (int i = 1; i <= 8; i++) {
                if(Integer.parseInt(str[i-1],2) == 0){
                    mav.put("data" + i + "left",25);
                }else if(Integer.parseInt(str[i-1],2) == 1){
                    mav.put("data" + i + "left",50);
                }else if(Integer.parseInt(str[i-1],2) == 2){
                    mav.put("data" + i + "left",75);
                }else if(Integer.parseInt(str[i-1],2) == 3){
                    mav.put("data" + i + "left",100);
                }
                if(Integer.parseInt(str[i+7],2) == 0){
                    mav.put("data" + i + "right",25);
                }else if(Integer.parseInt(str[i+7],2) == 1){
                    mav.put("data" + i + "right",50);
                }else if(Integer.parseInt(str[i+7],2) == 2){
                    mav.put("data" + i + "right",75);
                }else if(Integer.parseInt(str[i+7],2) == 3){
                    mav.put("data" + i + "right",100);
                }
            }
        }
        return AjaxResult.success(mav);
    }

    @ApiOperation("获取检测评估报告")
    @GetMapping("/queryReportUrl")
    @ResponseBody
    public AjaxResult queryReportUrl(@RequestParam Long userId,@RequestParam Long deviceDataId,@RequestParam String conclusion,@RequestParam String programme) throws Exception {
        return AjaxResult.success(commonService.queryReportUrl(userId,deviceDataId,conclusion,programme));
    }

    @GetMapping("/sendIm")
    @ResponseBody
    public AjaxResult sendIm(@RequestParam long userId,@RequestParam int position,@RequestParam int pointNum,@RequestParam String message) {
        commonService.sendIm(userId,position,pointNum,message);
        return AjaxResult.success();
    }

    @RequestMapping("footimg")
public ModelAndView footimg(){
    return new ModelAndView("footimg");
}

    /**
     * 通用请求设备（多个）
     */
    @PostMapping("/queryUser")
    @ResponseBody
    public AjaxResult queryUser() throws Exception {
        List<SysUser> userList = userService.selectUserList(new SysUser());
        return AjaxResult.success(userList);
    }

    @RequestMapping("test")
    public ModelAndView test(@RequestParam String deviceCode){
        ModelAndView mav = new ModelAndView();
        mav.setViewName("test");
        mav.addObject("deviceCode",deviceCode);
        return mav;
    }

    @RequestMapping("footwave")
    public ModelAndView footwave(){
        ModelAndView mav = new ModelAndView();
        mav.setViewName("footwave");
        return mav;
    }

    @RequestMapping("footwavehistory")
    public ModelAndView footwavehistory(){
        ModelAndView mav = new ModelAndView();
        mav.setViewName("footwavehistory");
        return mav;
    }

    @GetMapping("/sendImTest")
    @ResponseBody
    public AjaxResult sendImTest(@RequestParam Long userId,@RequestParam String message) {
        commonService.sendImTest(userId,message);
        return AjaxResult.success();
    }

    @RequestMapping("realtimeimg")
    public ModelAndView realtimeimg(@RequestParam Long userId){
        ModelAndView mav = new ModelAndView();
        mav.setViewName("realtimeimg");
        SysUser user = userService.selectUserById(userId);
        mav.addObject("user",user);
        if("0".equals(user.getSex())){
            mav.addObject("sex","男");
        }else if("1".equals(user.getSex())){
            mav.addObject("sex","女");
        }else{
            mav.addObject("sex","未知");
        }
        return mav;
    }

    @PostMapping("/sendLineIm")
    @ResponseBody
    public AjaxResult sendLineIm(@RequestParam Long userId,@RequestParam String startTime,@RequestParam String endTime) throws InterruptedException {
        commonService.sendLineIm(userId,startTime,endTime);
        return AjaxResult.success();
    }

    @PostMapping("/stopLineIm")
    @ResponseBody
    public AjaxResult stopLineIm(@RequestParam Long userId) throws InterruptedException {
        commonService.stopLineIm(userId);
        return AjaxResult.success();
    }

    @PostMapping("/queryUserByUserId")
    @ResponseBody
    public AjaxResult queryUserByUserId(@RequestParam Long userId) throws InterruptedException {
        return AjaxResult.success(commonService.queryUserByUserId(userId));
    }

    @PostMapping("/queryDeviceDataByUserId")
    @ResponseBody
    public AjaxResult queryDeviceDataByUserId(@RequestParam Long userId) throws InterruptedException {
        return AjaxResult.success(commonService.queryDeviceDataByUserId(userId));
    }

    @PostMapping("/sendUserId")
    @ResponseBody
    public AjaxResult sendUserId(@RequestParam Long userId) throws InterruptedException {
        commonService.sendUserId(userId);
        return AjaxResult.success();
    }

    @PostMapping("/sendUserIMTest")
    @ResponseBody
    public AjaxResult sendUserIMTest() throws InterruptedException {
        commonService.sendUserIMTest();
        return AjaxResult.success();
    }

    @RequestMapping("nettytest")
    public ModelAndView nettytest(){
        ModelAndView mav = new ModelAndView();
        mav.setViewName("nettytest");
        return mav;
    }

    @PostMapping("/queryDeviceDataById")
    @ResponseBody
    public AjaxResult queryDeviceDataById(@RequestParam Long deviceDataId){
        return AjaxResult.success("操作成功",commonService.queryDeviceDataById(deviceDataId));
    }

    @PostMapping("/queryDeviceByUserId")
    @ResponseBody
    public AjaxResult queryDeviceByUserId(@RequestParam Long userId){
        return AjaxResult.success("操作成功",commonService.queryDeviceByUserId(userId));
    }

    @PostMapping("/toiletLogin")
    @ResponseBody
    public AjaxResult toiletLogin(@RequestParam String username, @RequestParam String password){
        SysUser user = userService.selectUserByLoginName(username);
        String pass = passwordService.encryptPassword(username,password,user.getSalt());
        if(pass.equals(user.getPassword())){
            return AjaxResult.success("操作成功",user.getUserId().toString());
        }else{
            return AjaxResult.error("密码错误");
        }
    }

    @PostMapping("/addToiletData")
    @ResponseBody
    public AjaxResult addToiletData(@RequestParam String deviceCode, @RequestParam String message){
        deviceDataService.addToiletData(deviceCode,message);
        return AjaxResult.success();
    }

    @RequestMapping("toRoomReport")
    public ModelAndView toRoomReport(@RequestParam Long userId, @RequestParam String deviceCode){
        ModelAndView mav = new ModelAndView();
//        Long userId = commonService.queryUserIdByDeviceCode(deviceCode);
        mav.setViewName("roomReport");
        mav.addObject("userId",userId);
        mav.addObject("deviceCode",deviceCode);
        SysUser user = userService.selectUserById(userId);
        mav.addObject("user",user);
        if("0".equals(user.getSex())){
            mav.addObject("sex","男");
        }else if("1".equals(user.getSex())){
            mav.addObject("sex","女");
        }else{
            mav.addObject("sex","未知");
        }
//        LocalDateTime localDateTime = LocalDateTime.now().minus(1, ChronoUnit.HOURS);
//        String startTime = localDateTime.format(DateTimeFormatter.ofPattern(DateUtils.YYYY_MM_DD_HH_MM_SS));
//        String endTime = DateUtils.getTime();
        String date = DateUtils.getDate();
        String startTime = date + " 00:00:00";
        String endTime = date + " 24:00:00";
        Map<String,Object> map = commonService.queryRadarData(userId,deviceCode,startTime,endTime);
//        mav.addObject("radarData", map);
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        mav.addObject("radarData", gson.toJson(map));
        return mav;
    }

    @RequestMapping("roomReport")
    public ModelAndView roomReport(@RequestParam Long userId, @RequestParam String deviceCode){
        ModelAndView mav = new ModelAndView();
//        Long userId = commonService.queryUserIdByDeviceCode(deviceCode);
        mav.setViewName("roomReport1");
        mav.addObject("userId",userId);
        mav.addObject("deviceCode",deviceCode);
        SysUser user = userService.selectUserById(userId);
        mav.addObject("user",user);
        if("0".equals(user.getSex())){
            mav.addObject("sex","男");
        }else if("1".equals(user.getSex())){
            mav.addObject("sex","女");
        }else{
            mav.addObject("sex","未知");
        }
        return mav;
    }

    @RequestMapping("queryUser")
    public ModelAndView queryUser(@RequestParam Long userId){
        ModelAndView mav = new ModelAndView();
//        Long userId = commonService.queryUserIdByDeviceCode(deviceCode);
        mav.setViewName("user");
        mav.addObject("userId",userId);
        SysUser user = userService.selectUserById(userId);
        mav.addObject("user",user);
        if("0".equals(user.getSex())){
            mav.addObject("sex","男");
        }else if("1".equals(user.getSex())){
            mav.addObject("sex","女");
        }else{
            mav.addObject("sex","未知");
        }
        return mav;
    }

    @RequestMapping("/htmlToPdf")
    @ResponseBody
    public AjaxResult htmlToPdf() throws InterruptedException {
        HTMLToPDFUtils.htmlToImg("http://localhost:8009/common/toRoomReport?deviceCode=701D0808C659","C:\\123.jpg","");
        return AjaxResult.success();
    }

    /**
     * 微信登录
     */
    @ApiOperation("微信登录")
    @PostMapping("/radarWxLogin")
    @ResponseBody
    public AjaxResult radarWxLogin(@RequestParam("code") String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> paramMap = new HashMap<>();
//        paramMap.put("appid", "wx9144a8d802d22aaa");
//        paramMap.put("secret", "755af0ee1229fe9a6d346f50b44141e0");
        paramMap.put("appid", "wxa1984bf31494d947");
        paramMap.put("secret", "825354d156168501781aef7c7f3cbd8b");
//        paramMap.put("appid", "wx23e6d8a51f25e682");
//        paramMap.put("secret", "78b21d79a07e3cc377f221bd106e590a");
        paramMap.put("js_code", code);
        paramMap.put("grant_type", "authorization_code");
        String result = HttpOutSideUtil.getByHttp(url,paramMap);
        return AjaxResult.success(result);
    }

    /**
     * 微信登录
     */
    @ApiOperation("微信登录")
    @PostMapping("/breatheWxLogin")
    @ResponseBody
    public AjaxResult breatheWxLogin(@RequestParam("code") String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", "wx9ec379021028373b");
        paramMap.put("secret", "cbaef25214b5b72be61575e7e67913ab");
        paramMap.put("js_code", code);
        paramMap.put("grant_type", "authorization_code");
        String result = HttpOutSideUtil.getByHttp(url,paramMap);
        return AjaxResult.success(result);
    }

    @PostMapping("/exportPdf")
    @ResponseBody
    public AjaxResult exportPdf(@RequestParam Long userId, @RequestParam String deviceCode, @RequestParam Long surverId,@RequestParam String heartUrl,@RequestParam String respiratoryUrl,@RequestParam String sleepUrl,@RequestParam String sportsUrl,@RequestParam String scaleUrl,@RequestParam String date) throws InterruptedException {
        List<Map<String,Object>> subtitleList = new ArrayList<>();
        Map<String,Object> map = commonService.queryRadarData(userId,deviceCode,date + " 00:00:00",date + " 24:00:00");
        Map<String,Object> sleepCensus = new HashMap<>();
        sleepCensus.put("title","睡眠统计");
        sleepCensus.put("type","table");
        sleepCensus.put("tableType","1");
        Map<String,Object> sleepCensusMap = new HashMap<>();
        sleepCensusMap.put("recordStart", map.get("recordStart"));
        sleepCensusMap.put("recordEnd", map.get("recordEnd"));
        sleepCensusMap.put("totalRecord", map.get("totalRecord"));
        sleepCensusMap.put("totalSleep", map.get("totalSleep"));
        sleepCensusMap.put("sleepScale", map.get("sleepScale"));
        sleepCensus.put("content",sleepCensusMap);
        subtitleList.add(sleepCensus);

        Map<String,Object> sleepAnalyse = new HashMap<>();
        sleepAnalyse.put("title","睡眠分析");
        sleepAnalyse.put("type","table");
        sleepAnalyse.put("tableType","2");
        Map<String,Object> sleepAnalyseMap = new HashMap<>();
        sleepAnalyseMap.put("deepCumulative", map.get("deepCumulative"));
        sleepAnalyseMap.put("shallowCumulative", map.get("shallowCumulative"));
        sleepAnalyseMap.put("soberCumulative", map.get("soberCumulative"));
        sleepAnalyseMap.put("deepRatio", map.get("deepRatio"));
        sleepAnalyseMap.put("shallowRatio", map.get("shallowRatio"));
        sleepAnalyseMap.put("soberRatio", map.get("soberRatio"));
        sleepAnalyse.put("content",sleepAnalyseMap);
        subtitleList.add(sleepAnalyse);

        Map<String,Object> heartMap = new HashMap<>();
        heartMap.put("title","心率");
        heartMap.put("type","img");
        heartMap.put("content",heartUrl);
        subtitleList.add(heartMap);
        Map<String,Object> respiratoryMap = new HashMap<>();
        respiratoryMap.put("title","呼吸率");
        respiratoryMap.put("type","img");
        respiratoryMap.put("content",respiratoryUrl);
        subtitleList.add(respiratoryMap);
        Map<String,Object> sleepMap = new HashMap<>();
        sleepMap.put("title","睡眠状态");
        sleepMap.put("type","img");
        sleepMap.put("content",sleepUrl);
        subtitleList.add(sleepMap);
        Map<String,Object> sportsMap = new HashMap<>();
        sportsMap.put("title","运动体征");
        sportsMap.put("type","img");
        sportsMap.put("content",sportsUrl);
        subtitleList.add(sportsMap);
        Map<String,Object> scaleMap = new HashMap<>();
        scaleMap.put("title","睡眠质量");
        scaleMap.put("type","img");
        scaleMap.put("content",scaleUrl);
        subtitleList.add(scaleMap);
        Map<String,Object> answerMap = new HashMap<>();
        answerMap.put("title","问卷调查");
        answerMap.put("type","surver");
        answerMap.put("content",commonService.queryAnswer(userId,surverId));
        subtitleList.add(answerMap);
        return AjaxResult.success(commonService.exportPdf(userId,subtitleList));
    }

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/uploadBase64")
    @ResponseBody
    public AjaxResult uploadFileBase64(@RequestParam("file") String base64Data) throws Exception
    {
        try
        {
            BASE64DecodedMultipartFile file = (BASE64DecodedMultipartFile) Base64StrToImage.base64MutipartFile(base64Data);
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    @PostMapping("/getRadarData")
    @ResponseBody
    public AjaxResult getRadarData(@RequestParam Long userId, @RequestParam String deviceCode, @RequestParam(value = "date", required = false) String date) {
        Map<String,Object> map = new HashMap<>();
        if(StringUtils.isNull(date)) {
            LocalDateTime localDateTime = LocalDateTime.now().minus(1, ChronoUnit.HOURS);
            String startTime = localDateTime.format(DateTimeFormatter.ofPattern(DateUtils.YYYY_MM_DD_HH_MM_SS));
            String endTime = DateUtils.getTime();
            map = commonService.queryRadarData(userId,deviceCode,startTime,endTime);
        }else{
            String startTime = date + " 00:00:00";
            String endTime = date + " 24:00:00";
            map = commonService.queryRadarData(userId,deviceCode,startTime,endTime);
        }
        return AjaxResult.success(map);
    }

    @PostMapping("/addRadarUser")
    @ResponseBody
    public AjaxResult addRadarUser(@RequestParam("openid") String openid, @RequestParam("phone") String phone, @RequestParam("name") String name, @RequestParam("sex") String sex, @RequestParam("age") String age, @RequestParam("height") String height, @RequestParam("weight") String weight, @RequestParam("medical") String medical, @RequestParam("urgentName") String urgentName, @RequestParam("urgentPhone") String urgentPhone) {
        return AjaxResult.success(commonService.addRadarUser(openid,phone,name,sex,age,height,weight,medical,urgentName,urgentPhone));
    }

    @PostMapping("/queryRoomByUser")
    @ResponseBody
    public AjaxResult queryRoomByUser(@RequestParam("userId") Long userId) {
        return AjaxResult.success(commonService.queryRoomByUser(userId));
    }

    @PostMapping("/queryReport")
    @ResponseBody
    public AjaxResult queryReport(@RequestParam("userId") Long userId) {
        return AjaxResult.success(commonService.queryReport(userId));
    }

    @RequestMapping("toXdkManage")
    public ModelAndView toXdkManage(){
        ModelAndView mav = new ModelAndView();
        SysUser user = getSysUser();
        if(StringUtils.isNull(user)){
            mav.setViewName("login");
        }else {
            mav.setViewName("xdkManage");
            mav.addObject("userId", user.getUserId());
        }
        return mav;
    }

    @PostMapping("/radarLogin")
    @ResponseBody
    public AjaxResult radarLogin(@RequestParam String username, @RequestParam String password){
        SysUser user = userService.selectUserByLoginName(username);
        if(StringUtils.isNull(user)){
            return AjaxResult.error("用户不存在");
        }
        String pass = passwordService.encryptPassword(username,password,user.getSalt());
        if(pass.equals(user.getPassword())){
            return AjaxResult.success("操作成功",user.getUserId().toString());
        }else{
            return AjaxResult.error("密码错误");
        }
    }

    @PostMapping("/queryAllSurver")
    @ResponseBody
    public AjaxResult querySurver(){
        return AjaxResult.success(commonService.queryAllSurver());
    }

    @PostMapping("/addAnswer")
    @ResponseBody
    public AjaxResult addAnswer(@RequestBody(required = false) List<SurverAnswer> answerList){
        commonService.addAnswer(answerList);
        return AjaxResult.success();
    }

    @PostMapping("/queryAnswer")
    @ResponseBody
    public AjaxResult queryAnswer(@RequestParam Long userId, @RequestParam Long surverId){
        return AjaxResult.success(commonService.queryAnswer(userId,surverId));
    }

    @PostMapping("/queryRadarByUserId")
    @ResponseBody
    public AjaxResult queryRadarByUserId(@RequestParam Long userId){
        return AjaxResult.success("操作成功",commonService.queryRadarByUserId(userId));
    }

    @PostMapping("/queryRadarByUser")
    @ResponseBody
    public AjaxResult queryRadarByUser(@RequestParam Long userId){
        return AjaxResult.success("操作成功",commonService.queryRadarByUser(userId));
    }

    @Scheduled(cron="0 0 12 * * ?")
    @ApiOperation(value = "定时发送")
    @RequestMapping("/createPdf")
    @ResponseBody
    public void createPdf() throws IOException {
//        List<Map<String,Object>> list = new ArrayList<>();
        List<Map<String,Object>> roomList = commonService.queryPdfData();
//        List<Map<String,Object>> roomList = new ArrayList<>();
//        Map<String,Object> roomMap1 = new HashMap<>();
//        roomMap1.put("userId","111");
//        roomMap1.put("deviceCode","701D0808C659");
//        roomList.add(roomMap1);
        LocalDate localDate = LocalDate.now().minusDays(1);
        Date date = new Date();
        String startTime = localDate.format(DateTimeFormatter.ofPattern(DateUtils.YYYY_MM_DD)) + " " + DateUtils.parseDateToStr("HH:mm:ss",date);
        String endTime = DateUtils.getTime();
        for (Map<String,Object> roomMap:roomList) {
            List<Map<String,Object>> subtitleList = new ArrayList<>();
            Long userId = Long.valueOf(roomMap.get("userId").toString());
            String deviceCode = roomMap.get("deviceCode").toString();
            Map<String,Object> map = commonService.queryRadarData(userId,deviceCode,startTime,endTime);
//            Map<String,Object> map = commonService.queryRadarData(userId,deviceCode,null,null);
            commonService.insertSleepScale(userId,deviceCode,date,map);
//            Map<String,String> echartMap = commonService.creatEchartImg(userId,deviceCode,date,map);
//            Map<String,Object> m = new HashMap<>();
//            m.put("userId",userId);
//            m.put("echartUrl",echartMap);
//            list.add(m);
//            Map<String,Object> sleepCensus = new HashMap<>();
//            sleepCensus.put("title","睡眠统计");
//            sleepCensus.put("type","table");
//            sleepCensus.put("tableType","1");
//            Map<String,Object> sleepCensusMap = new HashMap<>();
//            sleepCensusMap.put("recordStart", map.get("recordStart"));
//            sleepCensusMap.put("recordEnd", map.get("recordEnd"));
//            sleepCensusMap.put("totalRecord", map.get("totalRecord"));
//            sleepCensusMap.put("totalSleep", map.get("totalSleep"));
//            sleepCensusMap.put("sleepScale", map.get("sleepScale"));
//            sleepCensus.put("content",sleepCensusMap);
//            subtitleList.add(sleepCensus);
//
//            Map<String,Object> sleepAnalyse = new HashMap<>();
//            sleepAnalyse.put("title","睡眠分析");
//            sleepAnalyse.put("type","table");
//            sleepAnalyse.put("tableType","2");
//            Map<String,Object> sleepAnalyseMap = new HashMap<>();
//            sleepAnalyseMap.put("deepCumulative", map.get("deepCumulative"));
//            sleepAnalyseMap.put("shallowCumulative", map.get("shallowCumulative"));
//            sleepAnalyseMap.put("soberCumulative", map.get("soberCumulative"));
//            sleepAnalyseMap.put("deepRatio", map.get("deepRatio"));
//            sleepAnalyseMap.put("shallowRatio", map.get("shallowRatio"));
//            sleepAnalyseMap.put("soberRatio", map.get("soberRatio"));
//            sleepAnalyse.put("content",sleepAnalyseMap);
//            subtitleList.add(sleepAnalyse);
//
//            Map<String,Object> heartMap = new HashMap<>();
//            heartMap.put("title","心率");
//            heartMap.put("type","img");
//            heartMap.put("content",echartMap.get("heartUrl"));
//            subtitleList.add(heartMap);
//            Map<String,Object> respiratoryMap = new HashMap<>();
//            respiratoryMap.put("title","呼吸率");
//            respiratoryMap.put("type","img");
//            respiratoryMap.put("content",echartMap.get("respiratoryUrl"));
//            subtitleList.add(respiratoryMap);
//            Map<String,Object> sleepMap = new HashMap<>();
//            sleepMap.put("title","睡眠状态");
//            sleepMap.put("type","img");
//            sleepMap.put("content",echartMap.get("sleepUrl"));
//            subtitleList.add(sleepMap);
//            Map<String,Object> sportsMap = new HashMap<>();
//            sportsMap.put("title","运动体征");
//            sportsMap.put("type","img");
//            sportsMap.put("content",echartMap.get("sportsUrl"));
//            subtitleList.add(sportsMap);
//            Map<String,Object> answerMap = new HashMap<>();
//            answerMap.put("title","问卷调查");
//            answerMap.put("type","surver");
//            answerMap.put("content",commonService.queryAnswer(userId,Long.valueOf(1)));
//            subtitleList.add(answerMap);
//            commonService.exportPdf(userId,subtitleList);
        }
    }

    @RequestMapping("/echartTest")
    @ResponseBody
    public AjaxResult echartTest(@RequestParam("userId") Long userId, @RequestParam("deviceCode") String deviceCode) {
        Date date = new Date();
        Map<String,Object> map = commonService.queryRadarData(userId,deviceCode,null,null);
        Map<String,String> echartMap = commonService.creatEchartImg(userId,deviceCode,date,map);
        Map<String,Object> m = new HashMap<>();
        m.put("userId",userId);
        m.put("echartUrl",echartMap);
        return AjaxResult.success("成功",m);
    }

    /**
     * 新增设备信息
     */
    @ApiOperation("新增设备信息")
    @PostMapping("/addDevice")
    @ResponseBody
    public AjaxResult addDevice(@RequestParam("userId") Long userId, @RequestParam("deviceCode") String deviceCode, @RequestParam("deviceName") String deviceName, @RequestParam("deviceType") Integer deviceType, @RequestParam("roomNum") String roomNum, @RequestParam("roomName") String roomName) throws Exception {
        AjaxResult ajax = commonService.addDevice(userId,deviceCode,deviceName,deviceType,roomNum,roomName);
        if(Integer.parseInt(ajax.get("code").toString()) == 0) {
            Map<String, Object> message = new HashMap<>();
            message.put("version", "1.0");
            message.put("method", "set");
            Map<String, Object> params = new HashMap<>();
            params.put("reportMode", "0");
            message.put("params", params);
            MqttUtil.send("/Radar60SP/" + deviceCode + "/sys/property/set", message);
            MqttUtil.subscribe("/Radar60SP/" + deviceCode + "/sys/property/post", new MessageListener());
        }
        return ajax;
    }

    /**
     * 新增异常信息
     */
    @ApiOperation("新增异常信息")
    @PostMapping("/addOmen")
    @ResponseBody
    public AjaxResult addOmen(@RequestParam("userId") Long userId, @RequestParam("omenListStr") String omenListStr) throws Exception {
        List<Map> omenList = JSON.parseArray(omenListStr,Map.class);
        commonService.addOmen(userId,omenList);
        return AjaxResult.success();
    }

    /**
     * 新增异常信息
     */
    @ApiOperation("新增异常信息")
    @PostMapping("/handleOmen")
    @ResponseBody
    public AjaxResult handleOmen(@RequestParam("userId") Long userId, @RequestParam("omenId") Long omenId) throws Exception {
        SysUser user = userService.selectUserById(userId);
        SysDeviceOmen deviceOmen = commonService.queryOmenById(omenId);
        if(StringUtils.isNotNull(user) && StringUtils.isNotNull(user.getEmail())) {
            SmsUtils.sendSms(user.getUrgentPhone(),user.getUrgentName(),deviceOmen.getOmenType(),user.getUserName(),user.getPhonenumber());
        }
        return AjaxResult.success("处理成功");
    }

    /**
     * 统计饼图
     */
    @ApiOperation("统计饼图")
    @PostMapping("/censusData")
    @ResponseBody
    public AjaxResult censusData() throws Exception {
        Map<String, Object> map = commonService.censusData();
        return AjaxResult.success(map);
    }

    /**
     * 查询用户信息
     */
    @ApiOperation("查询用户信息")
    @PostMapping("/queryUserById")
    @ResponseBody
    public AjaxResult queryUserById(@RequestParam("userId") Long userId) throws Exception {
        return AjaxResult.success(commonService.queryUserById(userId));
    }

    /**
     * 删除设备
     */
    @ApiOperation("删除设备")
    @PostMapping("/delDevice")
    @ResponseBody
    public AjaxResult delDevice(@RequestParam("userId") Long userId, @RequestParam("deviceCode") String deviceCode) throws Exception {
        commonService.delDevice(userId,deviceCode);
        return AjaxResult.success();
    }

    /**
     * 查询日月周数据
     */
    @ApiOperation("查询日月周数据")
    @PostMapping("/queryCensusData")
    @ResponseBody
    public AjaxResult queryCensusData(@RequestParam("userId") Long userId, @RequestParam("deviceCode") String deviceCode, @RequestParam("dataKey") String dataKey, @RequestParam("dateType") Integer dateType, @RequestParam("startTime") String startTime, @RequestParam(value="endTime",required = false) String endTime) throws Exception {
        return AjaxResult.success(commonService.queryCensusData(userId,deviceCode,dataKey,dateType,startTime,endTime));
    }

    /**
     * 发送邮件
     */
    @ApiOperation("发送邮件")
    @PostMapping("/sendMail")
    @ResponseBody
    public AjaxResult sendMail(@RequestParam("sendTo") String sendTo) throws Exception {
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message,true);
            //邮件发件人
            helper.setFrom("475297952@qq.com");
            //邮件收件人 1或多个
            helper.setTo(sendTo);
            //邮件主题
            helper.setSubject("测试");
            //邮件内容
            helper.setText("测试");
            //邮件发送时间
            helper.setSentDate(new Date());
//            FileSystemResource file = new FileSystemResource(new File("https://sunfu.xdkdate.com/profile/1-radar.pdf"));
//            helper.addAttachment("测试报告",file);
            javaMailSender.send(message);
            log.info("发送邮件成功:{}->{}","475297952@qq.com",sendTo);
        } catch (MessagingException e) {
            log.error("发送邮件时发生异常！",e);
        }
        return AjaxResult.success();
    }

    @ApiOperation("查询歌曲")
    @PostMapping("/querySong")
    @ResponseBody
    public AjaxResult querySong(@RequestParam(value = "keywords", required = false) String keywords) throws Exception {
        return AjaxResult.success(commonService.querySong(keywords));
    }

    /**
     * 通用请求设备（多个）
     */
    @PostMapping("/queryFootwave")
    @ResponseBody
    public AjaxResult queryFootwave() throws Exception {
        return AjaxResult.success(commonService.queryFootwave());

    }

    @RequestMapping("cushion")
    public ModelAndView cushion(){
//        MqttUtil.subscribe("/Radar60SP/a4cf12c1f5f4/sys/property/post",new MessageListener());
        return new ModelAndView("cushion");
    }

    @RequestMapping("shoepad")
    public ModelAndView shoepad(){
        return new ModelAndView("shoepad");
    }

    @PostMapping("/createGcode")
    @ResponseBody
    public AjaxResult createGcode(@Validated FootBean footBean) throws Exception {
        String fold = "F:\\Desktop\\鞋垫\\" + footBean.getShoesize();
        Path path = Paths.get(fold + "\\test.gcode");
        Files.delete(path);
        String footFile = fold + "\\" + footBean.getShoesize() + ".gcode";
        byte[] footBytes = Files.readAllBytes(Paths.get(footFile));
        String footContent = new String(footBytes, StandardCharsets.UTF_8);

        FileWriter fileWriter = new FileWriter(fold + "\\test.gcode",true);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter,1024);
        bufferedWriter.write(footContent);
        String[] leftFoot = footBean.getLeftfoot().split(",");
        for (int i = 0; i < leftFoot.length; i++) {
            byte[] bytes = Files.readAllBytes(Paths.get(fold + "\\" + footBean.getShoesize() + "-L-" + leftFoot[i] + ".gcode"));
            String content = new String(bytes, StandardCharsets.UTF_8);
            bufferedWriter.write(content);
        }
        String[] rightFoot = footBean.getRightfoot().split(",");
        for (int i = 0; i < rightFoot.length; i++) {
            byte[] bytes = Files.readAllBytes(Paths.get(fold + "\\" + footBean.getShoesize() + "-L-" + rightFoot[i] + ".gcode"));
            String content = new String(bytes, StandardCharsets.UTF_8);
            bufferedWriter.write(content);
        }
        bufferedWriter.write(" I\n" +
                "G0 F3000 X0 Y0");
        bufferedWriter.flush();
        bufferedWriter.close();
        return AjaxResult.success();

    }

    /**
     * 微信登录
     */
    @ApiOperation("微信登录")
    @PostMapping("/dressWxLogin")
    @ResponseBody
    public AjaxResult dressWxLogin(@RequestParam("code") String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> paramMap = new HashMap<>();
//        paramMap.put("appid", "wx9144a8d802d22aaa");
//        paramMap.put("secret", "755af0ee1229fe9a6d346f50b44141e0");
        paramMap.put("appid", "wxa1730a790aa26808");
        paramMap.put("secret", "7543a722d830ff7de788553dc7635697");
//        paramMap.put("appid", "wx23e6d8a51f25e682");
//        paramMap.put("secret", "78b21d79a07e3cc377f221bd106e590a");
        paramMap.put("js_code", code);
        paramMap.put("grant_type", "authorization_code");
        String result = HttpOutSideUtil.getByHttp(url,paramMap);
        return AjaxResult.success(result);
    }

    @PostMapping("/addDressUser")
    @ResponseBody
    public AjaxResult addDressUser(@RequestParam("openid") String openid, @RequestParam("phone") String phone, @RequestParam("name") String name, @RequestParam("sex") String sex, @RequestParam("age") String age, @RequestParam("height") String height, @RequestParam("weight") String weight, @RequestParam("urgentName") String urgentName, @RequestParam("urgentPhone") String urgentPhone) {
        return AjaxResult.success(commonService.addRadarUser(openid,phone,name,sex,age,height,weight,null,urgentName,urgentPhone));
    }

    @PostMapping("/saveDressData")
    @ResponseBody
    public AjaxResult saveDressData(@RequestParam("userId") Long userId, @RequestParam("dataKey") String dataKey, @RequestParam("dataValue") String dataValue) {
        commonService.saveDressData(userId,dataKey,dataValue, new Date());
        return AjaxResult.success();
    }

    @PostMapping("/queryDressDataYear")
    @ResponseBody
    public AjaxResult queryDressDataYear(@RequestParam("userId") Long userId, @RequestParam("dataKey") String dataKey) {
        return AjaxResult.success(commonService.queryDressDataYear(userId,dataKey));
    }

    @PostMapping("/queryDressDataMonth")
    @ResponseBody
    public AjaxResult queryDressDataMonth(@RequestParam("userId") Long userId, @RequestParam("dataKey") String dataKey) {
        return AjaxResult.success(commonService.queryDressDataMonth(userId,dataKey));
    }

    @PostMapping("/queryDressDataDay")
    @ResponseBody
    public AjaxResult queryDressDataDay(@RequestParam("userId") Long userId, @RequestParam("dataKey") String dataKey) {
        return AjaxResult.success(commonService.queryDressDataDay(userId,dataKey));
    }
}
